package meeting

import (
	"errors"
	"fmt"
	"log"
	"oa-rest/common"
	"oa-rest/models/message"
	"oa-rest/models/user"

	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

func (m *Meeting) saveMeeting(c *gin.Context) error {
	// 字段验证
	if err := m.validateFields(); err != nil {
		return err
	}

	_, err := common.DB.Transaction(func(session *xorm.Session) (interface{}, error) {
		m.Status = 1
		// 1.保存会议
		_, err := session.Insert(m)
		if err != nil {
			return nil, fmt.Errorf("保存会议失败: %v", err)
		}

		// 2.给参会人发送重要消息
		msgs := make([]*message.Message, 0)
		for _, member := range m.Attendee {
			if member == "" {
				continue // 跳过空参会人
			}
			msg := &message.Message{
				Receiver: member,
				Status:   1,
				Type:     1,    // 会议消息类型
				RefId:    m.Id, //会议id
				Priority: 1,
				Sender:   m.Promoter,
				RefName:  m.Title,
			}
			msgs = append(msgs, msg)
		}

		if len(msgs) > 0 {
			if _, err = session.Insert(&msgs); err != nil {
				return nil, fmt.Errorf("发送会议通知失败: %v", err)
			}
		}
		return nil, nil
	})
	return err
}

// validateFields 验证会议字段
func (m *Meeting) validateFields() error {
	if m.Title == "" {
		return errors.New("会议标题不能为空")
	}
	if len(m.Title) > 200 {
		return errors.New("会议标题长度不能超过200字符")
	}
	if m.Promoter == "" {
		return errors.New("发起人不能为空")
	}
	if len(m.Attendee) == 0 {
		return errors.New("参会人不能为空")
	}
	if m.PlanTime == "" {
		return errors.New("计划时间不能为空")
	}
	if m.Location == "" {
		return errors.New("会议地点不能为空")
	}
	// 验证时间格式
	if m.StartTime != "" && m.EndTime != "" {
		if m.StartTime >= m.EndTime {
			return errors.New("开始时间必须早于结束时间")
		}
	}
	return nil
}

func getMeetingList(c *gin.Context) (meetings []*Meeting, err error) {
	username := c.GetString("username")
	if username == "" {
		return nil, errors.New("no auth")
	}

	var meetings1 []*Meeting
	if err = common.DB.SQL("select * from meeting where status =1 order by start_time").Find(&meetings1); err != nil {
		return
	}

	for _, meeting := range meetings1 {
		// 1.获取当前登录用户发起的meeting列表
		if meeting.Promoter == username {
			// 填充参会人员真实姓名
			meeting.RealName = getRealNamesByUsernames(meeting.Attendee)
			meetings = append(meetings, meeting)
		} else {
			// 2.获取需要当前登录用户参加的meeting列表
			if Contains(meeting.Attendee, username) {
				// 填充参会人员真实姓名
				meeting.RealName = getRealNamesByUsernames(meeting.Attendee)
				meetings = append(meetings, meeting)
			}
		}
	}
	return
}

// getPendingMeetingList 获取当前登录人相关的待处理会议列表(status=1)
func getPendingMeetingList(c *gin.Context) (meetings []*Meeting, err error) {
	username := c.GetString("username")
	if username == "" {
		return nil, errors.New("no auth")
	}

	var meetings1 []*Meeting
	// 查询status=1的会议，按开始时间排序
	if err = common.DB.SQL("select * from meeting where status = 1 order by start_time").Find(&meetings1); err != nil {
		return
	}
	if username == "robot" {
		return meetings1, nil
	}

	for _, meeting := range meetings1 {
		// 1.获取当前登录用户发起的meeting列表
		if meeting.Promoter == username {
			// 填充参会人员真实姓名
			meeting.RealName = getRealNamesByUsernames(meeting.Attendee)
			meetings = append(meetings, meeting)
		} else {
			// 2.获取需要当前登录用户参加的meeting列表
			if Contains(meeting.Attendee, username) {
				// 填充参会人员真实姓名
				meeting.RealName = getRealNamesByUsernames(meeting.Attendee)
				meetings = append(meetings, meeting)
			}
		}
	}
	return
}

func Contains[T comparable](arr []T, target T) bool {
	for _, v := range arr {
		if v == target {
			return true
		}
	}
	return false
}

// getRealNamesByUsernames 根据用户名数组获取对应的真实姓名数组
func getRealNamesByUsernames(usernames []string) []string {
	if len(usernames) == 0 {
		return []string{}
	}

	// 批量查询用户真实姓名
	var users []*user.UsUser
	err := common.DB.In("user_name", usernames).Find(&users)
	if err != nil {
		log.Println("getRealNamesByUsernames查询失败:", err.Error())
		// 如果查询失败，返回空数组
		return make([]string, len(usernames))
	}

	// 创建用户名到真实姓名的映射
	nameMap := make(map[string]string)
	for _, u := range users {
		nameMap[u.UserName] = u.RealName
	}

	// 按原始顺序构建真实姓名数组
	realNames := make([]string, len(usernames))
	for i, username := range usernames {
		if realName, ok := nameMap[username]; ok {
			realNames[i] = realName
		} else {
			realNames[i] = "" // 如果用户不存在，返回空字符串
		}
	}

	return realNames
}
